//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.planw.beetl.sql.search;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.Processor;
import com.intellij.util.QueryParameters;
import com.planw.beetl.service.BeetlMapperService;
import com.planw.beetl.service.BeetlSqlService;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

public class BeetlSqlJavaMapperQueryExecutorBase extends QueryExecutorBase<PsiElement, QueryParameters> {
    private static final Logger logger = Logger.getInstance(BeetlSqlJavaMapperQueryExecutorBase.class);

    public BeetlSqlJavaMapperQueryExecutorBase() {
    }

    protected void toSearchSql(PsiClass psiClass, PsiMethod psiMethod, Processor<? super PsiElement> consumer) {
        Project project = psiClass.getProject();
        BeetlSqlService beetlSqlService = BeetlSqlService.getInstance(project);
        BeetlMapperService beetlMapperService = BeetlMapperService.getInstance(project);
        if (beetlMapperService.isBeetlMapper(psiClass)) {
            PsiFile sqlFile = beetlMapperService.findSqlFile(psiClass);
            if (sqlFile != null) {
                Map<PsiMethod, PsiElement> methodAndSqlIdMap = beetlMapperService.getMethodAndSqlIdMap(sqlFile, psiClass, psiMethod);
                PsiElement psiElement = (PsiElement) methodAndSqlIdMap.get(psiMethod);
                if (psiElement != null) {
                    consumer.process(psiElement);
                }

            }
        }
    }

    @Override
    public void processQuery(@NotNull QueryParameters queryParameters, @NotNull Processor<? super PsiElement> consumer) {
        if (queryParameters == null) {
            return;
        }

        if (consumer == null) {
            return;
        }

        if (queryParameters instanceof PsiTypeParameterListOwner) {
            if (queryParameters instanceof PsiMethod) {
                Application application = ApplicationManager.getApplication();
                application.runReadAction(() -> {
                    PsiMethod psiMethod = (PsiMethod) queryParameters;
                    PsiClass psiClass = psiMethod.getContainingClass();
                    if (null != psiClass) {
                        this.toSearchSql(psiClass, psiMethod, consumer);
                    }
                });
            }
        }
    }
}
